package com.zw.scancodelogin.utils;

import com.alibaba.fastjson.JSON;
import com.zw.scancodelogin.pojo.TokenInfo;
import com.zw.scancodelogin.pojo.WeChatUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class WeChatUtil {

    @Value("${wx.app.id}")
    private String APP_ID;

    @Value("${wx.app.secret}")
    private String APP_SECRET;

    private static String APPID;
    private static String APPSECRET;

    @PostConstruct
    public void init() {
        APPID = APP_ID;
        APPSECRET = APP_SECRET;
    }

    // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    public static WeChatUser getUserInfo(String code) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + APPSECRET + "&code=" + code + "&grant_type=authorization_code";

        String responseResult = restTemplate.getForObject(url, String.class);
        log.info("responseResult: {}", responseResult);

        TokenInfo tokenInfo = JSON.parseObject(responseResult, TokenInfo.class);

        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenInfo.getAccessToken() + "&openid=" + tokenInfo.getOpenid() + "&lang=zh_CN";
        String responseResult1 = restTemplate.getForObject(userInfoUrl, String.class);
        WeChatUser weChatUser = JSON.parseObject(responseResult1, WeChatUser.class);

        return weChatUser;
    }
}
